package com.supreme.stockserver.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.supreme.commonmybatis.mapper.StockMapper;
import com.supreme.commonentity.mysql.primary.BizStock;
import com.supreme.commonentity.mysql.primary.BizStockRecord;
import com.supreme.commonboot.utils.AjaxResp;
import com.supreme.stockserver.service.StockService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping(value = "stock")
public class StockController {

    @Resource
    private StockMapper stockMapper;

    @Resource
    private StockService stockService;

    @GetMapping(value = "search")
    public AjaxResp searchStock() {
        List<BizStock> selectList = this.stockMapper.selectList(Wrappers.emptyWrapper());
        return AjaxResp.instance(selectList);
    }

    @PostMapping(value = "create")
    public AjaxResp createStock(@RequestBody JSONObject bodyData) {
        final Long goodsId = bodyData.getLong("goodsId");
        final Integer stockNum = bodyData.getInteger("stockNum");
        stockService.createStock(goodsId, stockNum);
        return AjaxResp.instance();
    }

    @PutMapping(value = "update")
    public AjaxResp updateStock(@RequestBody JSONObject bodyData) {
        final Long stockId = bodyData.getLong("stockId");
        final Long userId = bodyData.getLong("userId");
        final Long orderId = bodyData.getLong("orderId");
        final Integer stockNum = bodyData.getInteger("stockNum");
        stockService.updateStock(stockId, userId, orderId, stockNum);
        return AjaxResp.instance();
    }

    @GetMapping(value = "searchRecordList")
    public AjaxResp searchStockRecordList(BizStockRecord stockRecordQuery) {
        final List<BizStockRecord> selectStockRecordList = stockService.selectStockRecordList(stockRecordQuery);
        return AjaxResp.instance(selectStockRecordList);
    }

    @GetMapping(value = "goodsStocks/{goodsId}")
    public AjaxResp goodsStocks(@PathVariable(value = "goodsId") Long goodsId,
                                @RequestParam(value = "stockNum", required = false) Integer stockNum) {
        final List<BizStock> stockList = stockService.getGoodsStock(goodsId, stockNum);
        return AjaxResp.instance(stockList);
    }

    @PutMapping(value = "stocks/{stockId}/{stockNum}")
    public AjaxResp updateStockNum(@PathVariable(value = "stockId") Long stockId,
                                   @PathVariable(value = "stockNum") Integer stockNum) {
        final int result = stockService.updateStockNum(stockId, stockNum);
        return AjaxResp.instance(result);
    }
}
